function [D tapping] = convert_script_fingertap(Sin)

% convert_script(inputdir,working_dir,subjid,subjinitials,runnum)
% 
% Converts .fif file to continuous spm data file
%
% subjid should be e.g. meg306
% subjinitials should be e.g. nsk
%
% MW

inputdir=Sin.inputdir;
working_dir=Sin.workingdir;
subjid=Sin.subjid; 
subjinitials=Sin.subjinitials;
fifbasename=Sin.fifbasename;
spmbasename=Sin.spmbasename;
runnum=Sin.runnum;

cd(working_dir);
S = [];
S.dataset = [inputdir '/' subjinitials fifbasename num2str(runnum) '.fif']
S.outfile = [spmbasename subjid '_' num2str(runnum)];
%S.path = working_dir;
S.channels = 'all';
S.checkboundary = 1;
S.usetrials = 1;
S.datatype = 'float32-le';
S.eventpadding = 0;
S.saveorigheader = 0;
S.conditionlabel = {'Undefined'};
S.inputformat = [];
S.continuous = true;
D = spm_eeg_convert(S);

% lowest possible value for a button press. Other button presses should be multiples
% of this
min_button_press_value=256;

eve=events(D,1);    

if(length(eve)>0)

tapping=zeros(length(D.time),1);

for i=1:length(eve),        
    val=eve(i).value;     
          
    % remove spurious button presses, or multiples thereof
    val=rem(val,min_button_press_value);
    eve(i).value=val;
    if(val==255)
        tapping(eve(i).time==D.time)=1;
    end;
           
    vals(i)=val; 
end;


h=hist(vals,unique(vals));
sfigure;bar(unique(vals),h);

if(isfield(Sin,'num_condition_trials_expected'))
    if(~isempty(Sin.num_condition_trials_expected))

        % check to see if correct number of events have been found
        uvals=unique(vals);

            wrong=0;
        for i=1:length(Sin.condition_code),
            ind=find(uvals==Sin.condition_code(i));

            xs(i)=ind;
            ys(i)=h(ind);

            if(ys(i)~=Sin.num_condition_trials_expected(i))
                wrong=1;
            end;
        end;

        sfigure;bar(1:4, ys-Sin.num_condition_trials_expected);

        if(wrong)
           warning('Wrong number of events');
           print('-dpng',[working_dir '/' S.outfile '_num_trials']);

           h=hist(vals,unique(vals));
           sfigure;bar(unique(vals),h);

           print('-dpng',[working_dir '/' S.outfile '_num_trials2']);

        else
           disp('Correct number of events');
        end;

    else
         warning('No events detected');
    end;
end;

end;

D=events(D,1,eve);

D.save;